package com.dragon.wangyiwork.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.dragon.wangyiwork.beans.AjaxResult;
import com.dragon.wangyiwork.entity.User;
import com.dragon.wangyiwork.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
    public String toLoginPage(){
        return "login";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public AjaxResult login(User user, HttpServletRequest request){
        HttpSession session = request.getSession();
        String message = "登录成功";
        if(StrUtil.isEmpty(user.getUsername())){
            message = "用户名不存在";
            return AjaxResult.error(message);
        }else {
            User userLogin = userService.userLogin(user);
            if (ObjectUtil.isNull(userLogin)) {
                message = "用户名或密码错误";
                return AjaxResult.error(message);
            }else {
                session.setAttribute("user",userLogin);
                return AjaxResult.success(message,userLogin);
            }
        }
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        return "login";
    }


}
